package org.elsa.fingobtb.common.utils

import java.security.MessageDigest

/**
 * btb 32位MD5加密算法
 *
 * @author valord577
 * @date 2018/7/16 16:37
 */
object MD5s {

    private val sb = StringBuilder()

    /**
     * 生成签名结果(新版本使用)
     */
    @Throws(Exception::class)
    fun buildMysignV1(param: Map<String, String>, secretKey: String): String {
        // 把数组所有元素，按照“参数=参数值”的模式用“&”字符拼接成字符串
        val preStr = createLinkString(param) + "secret_key=" + secretKey
        return getMD5String(preStr)
    }

    /**
     * 把数组所有元素排序，并按照“参数=参数值”的模式用“&”字符拼接成字符串
     */
    private fun createLinkString(param: Map<String, String>): String {
        val keys = ArrayList<String>(param.keys)
        keys.sort()

        // 重置StringBuilder
        sb.delete(0, sb.length)
        for (key in keys) {
            val value = param[key]
            sb.append(key).append("=").append(value).append("&")
        }
        return sb.toString()
    }

    /**
     * 生成32位大写MD5值
     */
    private val HEX_DIGITS =
            charArrayOf('0', '1', '2', '3', '4', '5', '6', '7', '8', '9', 'A', 'B', 'C', 'D', 'E', 'F')

    /**
     * MD5算法
     */
    @Throws(Exception::class)
    private fun getMD5String(str: String): String {
        var bytes = str.toByteArray()
        val messageDigest = MessageDigest.getInstance("MD5")
        messageDigest.update(bytes)
        bytes = messageDigest.digest()

        // 重置StringBuilder
        sb.delete(0, sb.length)
        for (i in bytes.indices) {
            sb.append(HEX_DIGITS[(bytes[i].toInt() and 0xf0) shr 4])
                    .append(HEX_DIGITS[bytes[i].toInt() and 0xf])
        }
        return sb.toString()
    }
}